﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CashResource;
using Cash.Model;
using CashCommon;
using System.Globalization;

namespace Cash.DialogFroms
{
    public partial class FormViewCash : Form
    {
        public FormViewCash(DateTime dtCash, string cashNumber, FormNewCash.FindConditions findCondition)
        {
            InitializeComponent();
            this.Text = CommonText.FormViewCashTitle;
            _dtCash = dtCash;
            _cashNumber = cashNumber;
            _findConditions = findCondition;
        }
        
        #region События

        private void ClickOnOk_Execute(object sender, EventArgs e)
        {
            if (!actionClickOnOk.Enabled)
                return;

            try
            {
                if (OnResultOk != null)
                    OnResultOk(Convert.ToInt32(dataGridCash.SelectedRows[0].Cells["LINK"].Value, CultureInfo.InvariantCulture));
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception err)
            {
                throw new ECash(MessageType.AllertLog, CommonError.FormViewCashClikcOkError, err);
            }
        }
        private void dataGridCash_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                ClickOnOk_Execute(null, null);
        }
        private void dataGridCash_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridCash.Columns[e.ColumnIndex].Name.Equals("N_Amount"))
            {
                e.Value = ((decimal)e.Value).ToString("C");
            }
            if (dataGridCash.Columns[e.ColumnIndex].Name.Equals("D_Date"))
            {
                e.Value = ((DateTime)e.Value).ToShortDateString();
            }
        }
        private void dataGridCash_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 && e.RowIndex == -1)
            {

                _backgroundWorker = new BackgroundWorker();
                _backgroundWorker.DoWork += new DoWorkEventHandler(bgwApplySettings);
                RunWorkerCompletedEventHandler rwc = new RunWorkerCompletedEventHandler(bgwCompletedApplySettings);
                _backgroundWorker.RunWorkerCompleted += rwc;
                _backgroundWorker.RunWorkerAsync();

                Adjustment.Default.CashGrid.Clear();
                Adjustment.Default.CashGrid.AddRange((
                    from DataGridViewColumn c in dataGridCash.Columns
                    select new GridColumn(c.Name, c.HeaderText, c.DisplayIndex, c.Width)).ToArray());
                if (dataGridCash.SortedColumn != null)
                {
                    Adjustment.Default.CashGrid.SortedColumn = dataGridCash.SortedColumn.Name;
                    Adjustment.Default.CashGrid.SortedAsc = dataGridCash.SortOrder == SortOrder.Ascending ? true : false;
                }
                Adjustment.Save();
                Adjustment.Load();
                System.Threading.Thread.Sleep(2000);
                bgwCompletedApplySettings(null, null);
            }
        }
        private void dataGridCash_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == -1 && e.RowIndex == -1)
            {
                Rectangle rectCell = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
                Rectangle rectPrint = new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 4, 14, 14);

                using (Brush gridBrush = new SolidBrush(this.dataGridCash.GridColor),
                        backColorBrush = new SolidBrush(e.CellStyle.BackColor),
                        backSelectedBrush = new SolidBrush(e.CellStyle.SelectionBackColor)
                        )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                            e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom - 1);
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                            e.CellBounds.Top, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom);

                        e.Graphics.DrawImage(Properties.Resources.Save, rectPrint);
                    }
                    e.Handled = true;
                }
            }
        }
        private void FormViewCash_Load(object sender, EventArgs e)
        {


            GetListCash();
            ApplySaveSettingToGrid();
        }

        #endregion

        #region Helper

        public void bgw_DoWorkForLoad(object sender, DoWorkEventArgs e)
        {
            SqlSwitch sqlSwitch = new SqlSwitch();
            switch (_findConditions)
            {
                case FormNewCash.FindConditions.Name:
                    sqlSwitch.Add("C_Name1", _cashNumber, SqlCondition.like, SqlType.sqlString, Direction.input);
                    break;
                case FormNewCash.FindConditions.Order:
                    sqlSwitch.Add("C_Order_Number", _cashNumber, SqlCondition.like, SqlType.sqlString, Direction.input);
                    break;
                default:
                    sqlSwitch.Add("N_Code", _cashNumber, SqlCondition.like, SqlType.sqlString, Direction.input);
                    break;
            }

            sqlSwitch.Add("F_Division", CashEmployer.Inst.F_Division, SqlCondition.in_enum, SqlType.sqlInt, Direction.input);
            if (this.dataGridCash.InvokeRequired)
                BeginInvoke(new MethodInvoker(delegate
                {
                    CashAccount.OpenSequence(dataGridCash, sqlSwitch, new List<string>() { "D_DATE", "N_CODE", "C_NAME1", "N_Amount" }, new OrderBy(new List<string>() { "D_DATE" }, true));
                }));
            else
            {
                CashAccount.OpenSequence(dataGridCash, sqlSwitch, new List<string>() { "D_DATE", "N_CODE", "C_NAME1", "N_Amount" }, new OrderBy(new List<string>() { "D_DATE" }, true));
            }
        }
        public void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_frmProgress != null)
                _frmProgress.Close();
            RefreshForm();
        }
        private void bgwApplySettings(object sender, DoWorkEventArgs e)
        {
            _frmProgress = new FrmProgress(CommonText.ProgressFormTitleSaveProperties);
            _frmProgress.ShowDialog();
        }
        private void bgwCompletedApplySettings(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_frmProgress != null)
                _frmProgress.DialogResult = DialogResult.OK;
        }
        public void RefreshForm()
        {
            bool RowsExist = dataGridCash.Rows.Count > 0;
            bool SelectExist = dataGridCash.SelectedRows.Count > 0;

            actionClickOnOk.Enabled = RowsExist && SelectExist;
        }
        private void ApplySaveSettingToGrid()
        {
            // Загрузка сохраненных настроек столбцов таблицы
            foreach (DataGridViewColumn item in dataGridCash.Columns)
            {
                GridColumn[] gridColumn = (
                    from GridColumn gridColumnItem in Adjustment.Default.CashGrid.Items
                    where gridColumnItem.Name == item.Name
                    select gridColumnItem
                    ).ToArray();
                if (gridColumn.Count() > 0)
                {
                    item.DisplayIndex = gridColumn[0].Position;
                    item.Width = gridColumn[0].Width;
                }
            }
            string sortColumn = Adjustment.Default.CashGrid.SortedColumn;
            if (Tools.AsNullString(sortColumn) != "")
                dataGridCash.Sort(dataGridCash.Columns[sortColumn],
                    Adjustment.Default.CashGrid.SortedAsc ? ListSortDirection.Ascending : ListSortDirection.Descending);
            if (dataGridCash.RowCount > 0)
                dataGridCash.Rows[0].Selected = true;
        }
        public void GetListCash()
        {
            _frmProgress = new FrmProgress(CommonText.ProgressFormTitleSearchCash);
            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += new DoWorkEventHandler(bgw_DoWorkForLoad);
            _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            _backgroundWorker.RunWorkerAsync();
            _frmProgress.ShowDialog();
        }
        #endregion

        #region Fields

        private DateTime _dtCash;
        private string _cashNumber;
        private FormNewCash.FindConditions _findConditions;
        private static FrmProgress _frmProgress;// = new FrmProgress(CommonText. ProgressFormTitleSearchCash);
        private static BackgroundWorker _backgroundWorker;
        
        #endregion

        #region Events
        
        public event DelegateFormResult OnResultOk;

        #endregion

        

    }
}
